package cn.stylefeng.guns.modular.system.workstation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.modular.deviceLedgerManagement.deviceLedger.entity.Equipment;
import cn.stylefeng.guns.modular.deviceLedgerManagement.deviceLedger.mapper.EquipmentMapper;
import cn.stylefeng.guns.modular.system.orgdata.entity.OrgData;
import cn.stylefeng.guns.modular.system.orgdata.mapper.OrgDataMapper;
import cn.stylefeng.guns.modular.system.workstation.pojo.response.StationVo;
import cn.stylefeng.roses.kernel.auth.api.context.LoginContext;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.guns.modular.system.workstation.entity.Station;
import cn.stylefeng.guns.modular.system.workstation.enums.StationExceptionEnum;
import cn.stylefeng.guns.modular.system.workstation.mapper.StationMapper;
import cn.stylefeng.guns.modular.system.workstation.pojo.request.StationRequest;
import cn.stylefeng.guns.modular.system.workstation.service.StationService;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.sys.modular.user.entity.SysUserOrg;
import cn.stylefeng.roses.kernel.sys.modular.user.mapper.SysUserMapper;
import cn.stylefeng.roses.kernel.sys.modular.user.mapper.SysUserOrgMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 工位信息表业务实现层
 *
 * @author PANL
 * @since 2023/12/05 14:22
 */
@Service
public class StationServiceImpl extends ServiceImpl<StationMapper, Station> implements StationService {

    @Autowired
    OrgDataMapper orgDataMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    EquipmentMapper equipmentMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(StationRequest stationRequest) {
        Station station = new Station();
        BeanUtil.copyProperties(stationRequest, station);
        this.save(station);//新增工位
        String stationCode = station.getStationCode();
        List<String> eqpids = stationRequest.getEqpids();
        if (eqpids != null && eqpids.size() > 0) {
            for (String eqpid : eqpids) {//绑定设备
                equipmentMapper.updateStation(eqpid, stationCode);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del(StationRequest stationRequest) {
        Station station = this.queryStation(stationRequest);
        this.removeById(station.getStationCode());//删除工位
        //修改设备绑定的工位为null
        equipmentMapper.updateStationToNull(stationRequest.getStationCode());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(StationRequest stationRequest) {
        this.removeByIds(stationRequest.getBatchDeleteIdList());
        List<String> batchDeleteIdList = stationRequest.getBatchDeleteIdList();
        for (String s : batchDeleteIdList) {
            equipmentMapper.updateStationToNull(s);//清空工位绑定设备
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(StationRequest stationRequest) {
        Station station = this.queryStation(stationRequest);
        BeanUtil.copyProperties(stationRequest, station);
        String stationCode = stationRequest.getStationCode();
        equipmentMapper.updateStationToNull(stationCode);//清空工位绑定设备
        List<String> eqpids = stationRequest.getEqpids();
        if (eqpids != null && eqpids.size() > 0) {
            for (String eqpid : eqpids) {
                equipmentMapper.updateStation(eqpid, stationCode);//绑定最新设备
            }
        }
        this.updateById(station);

    }

    @Override
    public StationVo detail(StationRequest stationRequest) {
        return this.queryStation(stationRequest);
    }

    @Override
    public PageResult<Station> findPage(StationRequest stationRequest) {
        List<String> list = new ArrayList<>();
        if (stationRequest.getORGID() != null) {
            //获取组织下的所有id（父级id+子集id工位信息）
            list = orgDataMapper.selectOrgid(stationRequest.getORGID());
        }
        LambdaQueryWrapper<Station> wrapper = createWrapper(stationRequest, list);
        Page<Station> pageList = this.page(PageFactory.defaultPage(), wrapper);
        return PageResultFactory.createPageResult(pageList);
    }

    @Override
    public Map config(String orgid) {
        String id = getOrgid(orgid);
        //获取组织下的用户配置
        List<Map> userlist = sysUserMapper.getUserListByOrgId(id);
        for (Map map : userlist) {
            map.put("USER_ID", map.get("USER_ID").toString());
        }
        //获取组织下的设备配置
        List<Equipment> equipmentList = equipmentMapper.selectList(new LambdaQueryWrapper<Equipment>().eq(Equipment::getOrgCode, orgid)
                .select(Equipment::getEqpCode, Equipment::getEQPNAME));
        Map map = new ConcurrentHashMap();
        map.put("userlist", userlist);
        map.put("equipmentList", equipmentList);
        return map;
    }


    @Override
    public List<Station> findList(StationRequest stationRequest) {
        List<String> list = new ArrayList<>();
        if (stationRequest.getORGID() != null) {
            //获取组织下的所有id（父级id+子集id工位信息）
            list = orgDataMapper.selectOrgid(stationRequest.getORGID());
        }
        LambdaQueryWrapper<Station> wrapper = this.createWrapper(stationRequest, list);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author PANL
     * @since 2023/12/05 14:22
     */
    private StationVo queryStation(StationRequest stationRequest) {
        Station station = this.getById(stationRequest.getStationCode());
        StationVo stationVo = new StationVo();
        BeanUtil.copyProperties(station, stationVo);
        stationVo.setEqpids(equipmentMapper.selectStation(stationRequest.getStationCode()));
        if (ObjectUtil.isEmpty(station)) {
            throw new ServiceException(StationExceptionEnum.STATION_NOT_EXISTED);
        }
        return stationVo;
    }

    /**
     * 创建查询wrapper
     *
     * @author PANL
     * @since 2023/12/05 14:22
     */
    private LambdaQueryWrapper<Station> createWrapper(StationRequest stationRequest, List<String> list) {
        LambdaQueryWrapper<Station> queryWrapper = new LambdaQueryWrapper<>();
        String stationCode = stationRequest.getStationCode();
        String stationName = stationRequest.getStationName();
      /*
        String createUser = stationRequest.getCreateUser();
        String createTime = stationRequest.getCreateTime();
        String updateUser = stationRequest.getUpdateUser();
        String updateTime = stationRequest.getUpdateTime();
        String ORGID = stationRequest.getORGID();


        queryWrapper.like(ObjectUtil.isNotEmpty(createUser), Station::getCreateUser, createUser);
        queryWrapper.eq(ObjectUtil.isNotNull(createTime), Station::getCreateTime, createTime);
        queryWrapper.like(ObjectUtil.isNotEmpty(updateUser), Station::getUpdateUser, updateUser);
        queryWrapper.eq(ObjectUtil.isNotNull(updateTime), Station::getUpdateTime, updateTime);
        queryWrapper.like(ObjectUtil.isNotEmpty(ORGID), Station::getORGID, ORGID);*/
        queryWrapper.like(ObjectUtil.isNotEmpty(stationCode), Station::getStationCode, stationCode);
        queryWrapper.like(ObjectUtil.isNotEmpty(stationName), Station::getStationName, stationName);
        queryWrapper.in(list.size() > 0, Station::getORGID, list);
        return queryWrapper;
    }

    /**
     * 最大组织id
     */
    String getOrgid(String orgid) {
        OrgData orgData = orgDataMapper.selectById(orgid);
        String orgPids = orgData.getOrgPids();
        String id = "";//最大组织id
        String[] split = orgPids.split(",");
        if (split.length == 1) {
            id = orgData.getOrgId().toString();
        } else {
            id = split[split.length - 1].replaceAll("\\[|\\]", "");
        }
        return id;
    }
}
